package com.darkflame.client.gui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.logging.Logger;

import com.darkflame.client.GreenFruitEnginev2;
import com.darkflame.client.SuperSimpleSemantics;
import com.darkflame.client.SpiffyWidgetsLite.SpiffyLoadingIcon_Lite;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Style.BorderStyle;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class TrustedIndexList extends SimplePanel {

	static HashSet<tickBar> trustedSiteList = new HashSet<tickBar>();
	static Logger Log = Logger.getLogger("gfe.TrustedIndexList");

	VerticalPanel siteList = new VerticalPanel();		
	HorizontalPanel refreshBar = new HorizontalPanel();

	public static CheckBox preloadOption = new CheckBox("Preload Index Contents"); 
	
	Button refreshButton = new Button("Load Indexs");
	Label warningLabel = new Label("(load at least one index before use)");

	VerticalPanel overallListBox = new VerticalPanel();
	DisclosurePanel mainContainer = new DisclosurePanel("Select indexs to use:");

	public static SpiffyLoadingIcon_Lite loadingicon = new SpiffyLoadingIcon_Lite(false);


	class tickBar extends HorizontalPanel{	

		CheckBox statebox = new CheckBox();
		String siteurl = "";

		public tickBar(String url,boolean state){			
			this.setWidth("100%");
			statebox.setValue(state);

			siteurl=url;
			Hyperlink urllink = new Hyperlink();
			urllink.setText(siteurl);
			urllink.setTargetHistoryToken("<ViewDatabase:"+siteurl+">");

			add(urllink);

			this.setHorizontalAlignment(ALIGN_RIGHT);
			add(statebox);


		}
		public boolean isTicked() {
			return statebox.getValue();
		}
		public String getSiteUrl() {
			return siteurl;
		}		
	}

	/** This is a currently a very crude/messy control box to select what Indexs
	 * you want the engine to use.
	 *  You need to hit "Refresh" after making your selections **/	
	public TrustedIndexList(){

		this.add(mainContainer);
		mainContainer.add(overallListBox);
		mainContainer.setOpen(true);

		//style it all
		this.getElement().getStyle().setBackgroundColor("#99AAFF");
		this.getElement().getStyle().setPadding(7, Unit.PX);
		this.getElement().getStyle().setBorderStyle(BorderStyle.SOLID);
		this.getElement().getStyle().setBorderWidth(2, Unit.PX);
		this.getElement().getStyle().setBorderColor("black");
		warningLabel.getElement().getStyle().setColor("Red");

		siteList.setWidth("100%");

		//this.add(new Label("Select indexs to use:"));		

		overallListBox.add(siteList);
		overallListBox.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		overallListBox.setSpacing(3);
		refreshBar.setSpacing(5);
		
		refreshBar.add(preloadOption);
		refreshBar.add(refreshButton);
		refreshBar.add(loadingicon);
		//loadingicon.setSize("70px", "70px");
		loadingicon.setPixelSize(30, 30);
		loadingicon.setVisible(false);
		loadingicon.setProgressLabelVisible(true);
		
		//connect loadingicon with supersimplesemantic database
		SuperSimpleSemantics.setGenericLoadingMonitor(TrustedIndexList.loadingicon);
		
		
		overallListBox.add(refreshBar);
		overallListBox.add(warningLabel);	
		
		preloadOption.addValueChangeHandler(new ValueChangeHandler<Boolean>() {			
			@Override
			public void onValueChange(ValueChangeEvent<Boolean> event) {
				
				SuperSimpleSemantics.setPreloadIndexs(event.getValue());
				
			}
		});
		preloadOption.setValue(true, true);

		refreshButton.addClickHandler(new ClickHandler() {			
			@Override
			public void onClick(ClickEvent event) {

				loadingicon.setVisible(true);

				//clear lists
				OverallInterface.clearLists();

				//load selected indexes after giving the interface a chance to update
				Scheduler.get().scheduleDeferred(new ScheduledCommand() {    					
					@Override
					public void execute() {						
						//start the loading!
						ArrayList<String> trsuedSites=TrustedIndexList.getAllCheckedSites();	
						
						GreenFruitEnginev2.loadIndexsAt(trsuedSites);
						
					}});

			}
		});
	}
	
	public void cleanUpAfterLoad(){
			
		TrustedIndexList.loadingicon.setVisible(false);
		warningLabel.setVisible(false);				
		mainContainer.setOpen(false);
		Log.info("-------------------------------------------------------------------------------------------");
		
	}

	public void addSite(String url,boolean defaultState){

		tickBar newtb=new tickBar(url, defaultState);

		//trustedSiteList.put(url, true);
		siteList.add(newtb);
		trustedSiteList.add(newtb);
	}

	static public ArrayList<String> getAllCheckedSites(){



		ArrayList<String> results = new ArrayList<String>();

		Iterator<tickBar> trustedit = trustedSiteList.iterator();

		while (trustedit.hasNext()) {

			tickBar sitebars = (tickBar) trustedit.next();

			if (sitebars.isTicked()){


				results.add(sitebars.getSiteUrl());



			}
		}



		return results;
	}


	/** takes a url to a simple text file list
	 * then adds all the lines in the file to the database list **/
	public void addSitesFrom(String fileurl) {

		RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,
				fileurl);

		final TrustedIndexList thislist = this; 

		try {
			requestBuilder.sendRequest("",new RequestCallback(){

				@Override
				public void onResponseReceived(Request request, Response response) {

					String databaselines = response.getText();
					String urls[] = databaselines.split("\r?\n|\r");

					for (String url : urls) {

						thislist.addSite(url, false);

					}


				}

				@Override
				public void onError(Request request, Throwable exception) {
					// TODO Auto-generated method stub

				}

			});
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}






	}

}
